const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const {jwtSecreKey} = require('../config/jwtSecreKey')
/**
 * 注册接口逻辑
 */
exports.registerController = (req, res) => {
    // 用户名或密码判空的校验
    let { loginname, password, username } = req.body;
    if (!loginname || !password || !username) {
        return res.send({ code: 1, message: '登录名,密码,用户名都不能为空！' });
    };
    // 用户名查重的逻辑
    const userSlectSql = 'select * from cms_user where loginname = ?'
    db.query(userSlectSql, loginname, (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        // 判断用户是否在数据库中存在
        if (result.length > 0) {
            return res.send({ code: 1, message: '该用户名已经存在' });
        }
        // 用户密码加密
        const bcrypt = require('bcryptjs');
        const passworddB = bcrypt.hashSync(password, 10)
        // 用户随机生成头像
        const imgList = [
            '../../public/images/图片资源/cb5c25b1dd0ed745c11a18847c7faaab.png'
        ]
        const num = Math.floor(Math.random() * 10 + 1);
        // 用户信息插入数据库
        const userInsertSql = 'insert into cms_user (loginname, password, username, img) value ( ?, ?, ?, ?)'
        db.query(userInsertSql, [loginname, passworddB, username, imgList[0]], (err, result) => {
            if (err) {
                return res.send({ code: 1, message: err.message });
            };
            res.send({
                code: 0,
                message: '注册成功',
            })
        })
    })
};

/**
 * 登录接口逻辑
 */
exports.loginController = (req, res) => {
    let { loginname, password } = req.body;
    const userSelectSql = 'select * from cms_user where loginname = ?'
    db.query(userSelectSql, loginname, (err, result) => {
        if (err) {
            return res.send({ code: 1, message: err.message });
        }
        // 账号存在是否判断
        if (result.length === 0 || result[0].del == 1) {
            return res.send({ code: 1, message: '账号不存在，请先注册' });
        };
        // 判断密码是否正确
        const compareState = bcrypt.compareSync(password, result[0].password)
        if (!compareState) {
            return res.send({ code: 1, message: '密码错误'})
        }

        console.log(result[0].del)
        const user = {...result[0], pwd:''};
        const token = jwt.sign(user, jwtSecreKey, {expiresIn: '24h'})

        res.send({ code: 0, message:'登陆成功', token:'Bearer ' + token})
    });
}

/**
 * 当前用户信息查询逻辑
 */
exports.userInfoController = (req, res) => {
    // 获取token
    const token = req.headers.authorization
    const userInfo = jwt.verify(token.split('Bearer ')[1], jwtSecreKey);
    // 解析token
    res.send({code: 0, data:{username: userInfo.loginname , img: userInfo.img}});
};